package com.example.demo.web.util;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.example.demo.web.services.GateWayService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;

@Component
public class RabbitAckReceiver implements ChannelAwareMessageListener {
	private ObjectMapper mapper; 
    private com.fasterxml.jackson.databind.JsonNode rootNode;
    @Autowired
    private GateWayService gatewayService;
    
	@Override
    public void onMessage(Message message, Channel channel) throws Exception {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        byte[] body = message.getBody();
        mapper = new ObjectMapper(); 
        
		rootNode = mapper.readTree(new String(body));
		try {
			String reqtype = rootNode.get("type").asText();
			
			if(reqtype.equalsIgnoreCase("userAuth")) {
				gatewayService.GateWayParseAuth(rootNode);
			}else if(reqtype.equalsIgnoreCase("openreport")) {
				gatewayService.HandleOpenReport(rootNode);
			}
			
			channel.basicAck(deliveryTag, true);
			
		}catch(Exception e) {
			channel.basicReject(deliveryTag, false);
			e.printStackTrace();
		}
    }

}
